﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using MTBrainStorm.Framework;
using MTBrainStorm.Models.VirtualKeyboard;
using MTBrainStorm.Models.VirtualKeyboard.VirtualKeyCodes;

namespace MTBrainStorm.ViewModels
{
	public class VirtualKeyboardViewModel : MultiTouchElementViewModel
	{
		#region props
		
		private Dictionary<string, VirtualKeyboardKeyViewModel> _keys = new Dictionary<string, VirtualKeyboardKeyViewModel>();
		public Dictionary<string, VirtualKeyboardKeyViewModel> Keys
		{
			get { return _keys; }
			set { _keys = value; }
		}

		private string _text;
		public string Text
		{
			get
			{
				return _text;
			} 
			set 
			{ 
				_text = value;
				RaisePropertyChanged("Text");
			} 
		}

		private readonly VirtualKeyboardModel _model = new VirtualKeyboardModel();

		#endregion

		#region commands
		
		private RelayCommand<Characters> _pressKeyCommand;

		public ICommand PressKeyCommand
		{
			get { return _pressKeyCommand ?? (_pressKeyCommand = new RelayCommand<Characters>(key => Text = Text + _model.GetCharacter((Characters)key.GetHashCode()))); }
		}

		private RelayCommand<Specials> _pressSpecialKeyCommand;

		public ICommand PressSpecialKeyCommand
		{
			get { return _pressSpecialKeyCommand ?? (_pressSpecialKeyCommand = new RelayCommand<Specials>(ExecuteSpecialKey)); }
		}

		#endregion

		#region methods

		private void ExecuteSpecialKey(Specials key)
		{
			switch (key)
			{
				case Specials.Backspace:
					if (Text.Length > 0)
						Text = Text.Substring(0, Text.Length - 1);
					break;
				case Specials.Space:
					Text = Text + " ";
					break;
				case Specials.CapsLock:
					_model.ToggleCapsLock();
					break;
			}
		}

		#endregion

		#region constructors

		public VirtualKeyboardViewModel()
		{
			Text = string.Empty;
		    Width = 530;
		    Height = 350;

			foreach (var value in Enum.GetValues(typeof(Characters)))
			{
				_keys.Add(value.ToString(), new VirtualKeyboardCharKeyViewModel((Characters)value, PressKeyCommand));
			}

			foreach (var value in Enum.GetValues(typeof(Specials)))
			{
				_keys.Add(value.ToString(), new VirtualKeyboardSpecialKeyViewModel(value.ToString(), (Specials)value, PressSpecialKeyCommand));
			}
		}

		#endregion
	}
}
